package xyz.zdsoft.user_info_manage_module.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import xyz.zdsoft.common.entity.ClassStudentInfo;
import xyz.zdsoft.common.entity.SysUser;
import xyz.zdsoft.common.service.impl.ClassInfoServiceImpl;
import xyz.zdsoft.common.service.impl.ClassStudentInfoServiceImpl;
import xyz.zdsoft.common.service.impl.SysUserServiceImpl;
import xyz.zdsoft.common.utils.Result;
import xyz.zdsoft.user_info_manage_module.mapper.StudentInoManagementMapper;
import xyz.zdsoft.user_info_manage_module.pojo.*;
import xyz.zdsoft.user_info_manage_module.service.StudentInfoManagementService;

import javax.annotation.Resource;

/**
 * 学生信息管理业务逻辑处理接口实现类
 * @author 以风
 */
@Service
public class StudentInfoManagementServiceImpl implements StudentInfoManagementService {
    @Resource
    private StudentInoManagementMapper studentInoManagementMapper;

    @Resource
    private ClassStudentInfoServiceImpl classStudentInfoService;

    @Resource
    private ClassInfoServiceImpl classInfoService;

    @Resource
    private SysUserServiceImpl sysUserService;

    /**
     * 获取班级信息分页列表（查询、分页、重置）
     *
     * @param page               分页参数
     * @param classInfoParameter 班级信息参数
     * @return 班级信息分页列表
     */
    @Override
    public IPage<ClassInfo> getClassInfoPage(IPage<ClassInfo> page, ClassInfoParameter classInfoParameter) {
        //获取班级信息分页列表
        IPage<ClassInfo> classInfoIPage = studentInoManagementMapper.getClassInfoPage(page,classInfoParameter);
        //获取班级学员数
        for (ClassInfo classInfo : classInfoIPage.getRecords()){
            QueryWrapper<ClassStudentInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("class_info_id",classInfo.getId());
            int count = classStudentInfoService.count(wrapper);
            classInfo.setStudentTotal(count);
        }
        return classInfoIPage;
    }

    /**
     * 学员明细分页列表(查询、分页、重置)
     *
     * @param page                        分页参数
     * @param studentsSubsidiaryParameter 学员信息参数
     * @return 学员明细分页列表
     */
    @Override
    public IPage<StudentsSubsidiary> getStudentsSubsidiaryPage(IPage<StudentsSubsidiary> page, StudentsSubsidiaryParameter studentsSubsidiaryParameter) {
        IPage<StudentsSubsidiary> studentsSubsidiaryIPage = studentInoManagementMapper.getStudentsSubsidiaryPage(page,studentsSubsidiaryParameter);
        //如果有学员
        if (studentsSubsidiaryIPage.getRecords() != null){
            //获取班主任
            String classTeacher = studentInoManagementMapper.getClassTeacher(studentsSubsidiaryParameter.getId());
            for (StudentsSubsidiary subsidiary : studentsSubsidiaryIPage.getRecords()){
                subsidiary.setClassTeacher(classTeacher);
            }
        }
        return studentsSubsidiaryIPage;
    }

    /**
     * 新增班级
     * @param insertClassParameter 新增班级信息入参
     * @return 新增班级结果：0：失败，1：成功
     */
    public Result insertClass(InsertClassParameter insertClassParameter) {
        QueryWrapper<xyz.zdsoft.common.entity.ClassInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("colleges_id",insertClassParameter.getCollegesId())
                .eq("major_id",insertClassParameter.getMajorId())
                .eq("grade_info_id",insertClassParameter.getGradeInfoId())
                .eq("class_base_info_id",insertClassParameter.getClassBaseInfoId());
        int existing = classInfoService.count(wrapper);
        if (existing > 0){
            return Result.error().message("已存在相同班级信息").data(0);
        }else {
            //新增班级
            xyz.zdsoft.common.entity.ClassInfo commonClassInfo = new xyz.zdsoft.common.entity.ClassInfo();
            //院系
            commonClassInfo.setCollegesId(insertClassParameter.getCollegesId());
            //专业
            commonClassInfo.setMajorId(insertClassParameter.getMajorId());
            //年级
            commonClassInfo.setGradeInfoId(insertClassParameter.getGradeInfoId());
            //班级号
            commonClassInfo.setClassBaseInfoId(insertClassParameter.getClassBaseInfoId());
            //班主任
            commonClassInfo.setTeacherId(insertClassParameter.getTeacherId());
            //是否已结业
            commonClassInfo.setIsGraduation(insertClassParameter.getIsGraduation());

            //TODO 创建者

            //todo 创建时间

            boolean flag = classInfoService.save(commonClassInfo);
            if (flag){
                return Result.ok().message("新增班级成功").data(1);
            }else {
                return Result.error().message("新增班级失败").data(0);
            }
        }
    }

    /**
     * 编辑班级
     * @param editClassInfoParameter 编辑班级信息入参
     * @return 编辑班级结果：0：失败，1：成功
     */
    public Result editClassInfo(EditClassInfoParameter editClassInfoParameter) {
        QueryWrapper<xyz.zdsoft.common.entity.ClassInfo> editWrapper = new QueryWrapper<>();
        editWrapper.eq("colleges_id",editClassInfoParameter.getCollegesId())
                   .eq("major_id",editClassInfoParameter.getMajorId())
                   .eq("grade_info_id",editClassInfoParameter.getGradeInfoId())
                   .eq("class_base_info_id",editClassInfoParameter.getClassBaseInfoId());
        int existing = classInfoService.count(editWrapper);
        if (existing > 0){
            return Result.error().message("已存在相同班级信息").data(0);
        }else {
            //编辑班级
            xyz.zdsoft.common.entity.ClassInfo commonEditClassInfo = new xyz.zdsoft.common.entity.ClassInfo();
            //主键
            commonEditClassInfo.setId(editClassInfoParameter.getId());
            //院系
            commonEditClassInfo.setCollegesId(editClassInfoParameter.getCollegesId());
            //专业
            commonEditClassInfo.setMajorId(editClassInfoParameter.getMajorId());
            //年级
            commonEditClassInfo.setGradeInfoId(editClassInfoParameter.getGradeInfoId());
            //班级号
            commonEditClassInfo.setClassBaseInfoId(editClassInfoParameter.getClassBaseInfoId());
            //班主任
            commonEditClassInfo.setTeacherId(editClassInfoParameter.getTeacherId());
            //是否已结业
            commonEditClassInfo.setIsGraduation(editClassInfoParameter.getIsGraduation());

            //TODO 更新者

            boolean flag = classInfoService.updateById(commonEditClassInfo);
            if (flag){
                return Result.ok().message("修改班级信息成功").data(1);
            }else {
                return Result.error().message("修改班级信息失败").data(0);
            }
        }
    }

    /**
     * 学员明细-新增
     * @param insertStudentSubsidiary 新增学员信息入参
     * @return 新增结果：0：失败，1：成功
     */
    public Result insertStudent(InsertStudentSubsidiary insertStudentSubsidiary) {
        //查询学生是否存在
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("name",insertStudentSubsidiary.getStudentName())
                .eq("user_no",insertStudentSubsidiary.getUserNo())
                .eq("sex",insertStudentSubsidiary.getSex())
                .eq("id_no",insertStudentSubsidiary.getIdNo())
                .eq("email",insertStudentSubsidiary.getEmail())
                .eq("mobile_no",insertStudentSubsidiary.getMobileNo())
                .eq("position",insertStudentSubsidiary.getPosition())
                .last("LIMIT 1");
        SysUser student =  sysUserService.getOne(wrapper);
        System.out.println("查询到的学生id" + student.getId());
        //如果学生存在
        if (student != null){
            //查询该学生是否已加入该班级或其它班级
            QueryWrapper<ClassStudentInfo> csWrapper = new QueryWrapper<>();
            csWrapper.eq("student_id",student.getId())
                     .last("LIMIT 1");
            ClassStudentInfo classStudentInfo = classStudentInfoService.getOne(csWrapper);
            //如果该学生已加入该班级
            if (classStudentInfo != null){
                return Result.error().message("该用户已加入该班级或其它班级，不允许重复添加").data(0);
            }else {
                //如果该学生没有加入到该班级，将该学生加入到该班级
                ClassStudentInfo classStudentInfo1 = new ClassStudentInfo();
                classStudentInfo1.setStudentId(student.getId());
                classStudentInfo1.setClassInfoId(insertStudentSubsidiary.getId());
                boolean flag = classStudentInfoService.save(classStudentInfo1);
                if (flag){
                    return Result.ok().message("新增学员成功").data(1);
                }else {
                    return Result.error().message("新增学员失败").data(0);
                }
            }
        }else {
            //如果学生不存在
            return Result.error().message("该学生信息尚未录入系统，请录入系统后添加").data(0);
        }
    }

    /**
     * 学员明细-编辑（学员信息维护）
     * @param editStudentSubsidiary 编辑学员信息入参
     * @return 编辑结果：0：失败，1：成功
     */
    public Result editStudentsSubsidiary(EditStudentSubsidiary editStudentSubsidiary) {
        //先根据学生id查询学号
        SysUser sysUser = sysUserService.getById(editStudentSubsidiary.getId());
        //如果学号与当前用户相同，可修改当前用户信息
        if (sysUser.getUserNo().equals(editStudentSubsidiary.getUserNo())){
            //根据学生id修改学生信息
            SysUser student = new SysUser();
            //主键
            student.setId(editStudentSubsidiary.getId());
            //姓名
            student.setName(editStudentSubsidiary.getStudentName());
            //学号
            student.setUserNo(editStudentSubsidiary.getUserNo());
            //性别
            student.setSex(editStudentSubsidiary.getSex());
            //身份证号码
            student.setIdNo(editStudentSubsidiary.getIdNo());
            //邮箱
            student.setEmail(editStudentSubsidiary.getEmail());
            //手机号
            student.setMobileNo(editStudentSubsidiary.getMobileNo());
            //项目角色
            student.setPosition(editStudentSubsidiary.getPosition());

            //TODO 修改者

            boolean flag = sysUserService.updateById(student);
            if (flag){
                return Result.ok().message("编辑学员信息成功").data(1);
            }else {
                return Result.error().message("编辑学员信息失败").data(0);
            }
        }else {
            //如果学号与当前用户不同，则查询该学号是否被占用
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("user_no",editStudentSubsidiary.getUserNo());
            int count = sysUserService.count(wrapper);
            //如果该学号被占用
            if (count > 0){
                return Result.error().message("该学号已存在，请重新编辑").data(0);
            }else {
                //学号没被占用，根据学生id修改学生信息
                SysUser student1 = new SysUser();
                //主键
                student1.setId(editStudentSubsidiary.getId());
                //姓名
                student1.setName(editStudentSubsidiary.getStudentName());
                //学号
                student1.setUserNo(editStudentSubsidiary.getUserNo());
                //性别
                student1.setSex(editStudentSubsidiary.getSex());
                //身份证号码
                student1.setIdNo(editStudentSubsidiary.getIdNo());
                //邮箱
                student1.setEmail(editStudentSubsidiary.getEmail());
                //手机号
                student1.setMobileNo(editStudentSubsidiary.getMobileNo());
                //项目角色
                student1.setPosition(editStudentSubsidiary.getPosition());

                //TODO 修改者

                boolean flag = sysUserService.updateById(student1);
                if (flag){
                    return Result.ok().message("编辑学员信息成功").data(1);
                }else {
                    return Result.error().message("编辑学员信息失败").data(0);
                }
            }
        }
    }

    /**
     * 学员明细-删除（批量删除）
     * @param id 班级id
     * @param studentsId 学生id数组
     * @return 删除结果：0：失败，1：成功
     */
    public Result deleteStudents(long id, Long[] studentsId) {
        boolean flag = false;
        for (Long studentId : studentsId){
            QueryWrapper<ClassStudentInfo> wrapper = new QueryWrapper();
            wrapper.eq("class_info_id",id);
            wrapper.eq("student_id",studentId);
            flag =  classStudentInfoService.remove(wrapper);
        }
        if (flag){
            return Result.ok().message("删除学员信息成功").data(1);
        }else {
            return Result.error().message("删除学员信息失败").data(0);
        }
    }
}
